package config

import (
	"github.com/BurntSushi/toml"
	"github.com/Unixeno/TheMoon/common/constants"
	"github.com/Unixeno/TheMoon/logging"
	"os"
)

type PlanetConfig struct {
	ConfigFilename string
	LogLevel       string
	ServerID       string // server id，在与moon通信时会被用于证书验证

	Station    StationConfig
	Gateway    GatewayConfig
	Statistics StatisticsConfig
}

type StationConfig struct {
	// 心跳包时间，默认值10秒
	Heartbeat int32
	// 读取超时时间，默认值15秒
	ReadDeadline int32
	// 发送超时时间，默认值15秒
	WriteDeadline int32
	// 客户端类型
	ClientType string
	// 服务端地址
	Server string
	// 证书ca文件路径
	CAFile string
	// 证书文件路径
	CertFile string
	// 证书私钥路径
	PrivateKeyFile string
	// 是否启用严格客户端证书检查
	VerifyClient bool
}

type GatewayConfig struct {
	Addr string
}

type StatisticsConfig struct {
	InfluxDB string // influxdb 链接信息
	DBName   string // influxdb 数据库
}

var SysConfig = newBasicConfig()
var logger = logging.GetLogger("config")

func Init() error {
	filename := os.Getenv("CONFIG_PATH")
	if filename != "" {
		SysConfig.ConfigFilename = filename
	}
	logger.Infof("load configure file from %s", SysConfig.ConfigFilename)
	return SysConfig.Parse()
}

func newBasicConfig() *PlanetConfig {
	return &PlanetConfig{
		ConfigFilename: "./planet.toml",
		LogLevel:       "debug",
		ServerID:       constants.DefaultPlanetID,
		Station: StationConfig{
			Heartbeat:      constants.DefaultHeartbeat,
			ReadDeadline:   constants.DefaultReadDeadline,
			WriteDeadline:  constants.DefaultWriteDeadline,
			ClientType:     constants.DefaultClientType,
			Server:         constants.DefaultServer,
			CAFile:         "cert/ca.pem",
			CertFile:       "cert/planet.pem",
			PrivateKeyFile: "cert/planet.key",
		},
		Gateway: GatewayConfig{
			Addr: constants.DefaultGateway,
		},
		Statistics: StatisticsConfig{
			InfluxDB: "http://localhost:8086",
			DBName:   "statistics",
		},
	}
}

func (c *PlanetConfig) Parse() error {
	_, err := toml.DecodeFile(c.ConfigFilename, c)
	return err
}
